// components/login/login.js
import Util from '../../utils/utils';
import User from '../../utils/user';
import Dialog from '../../dist/dialog/dialog';

const app = getApp();
Component({
  /**
   * 组件的初始数据
   */
  properties: {
    type: {
      type: String,
      value: 'basic'
    }, // 是否显示迷你登录按钮
    btnText: {
      type: String,
      value: '微信授权登录'
    },
    btnMsg: {
      type: String,
      value: ''
    }
  },
  data: {
    cancelTotal: 0,
    showReadMe: false,
    code: '',
    imgUrl: Util.pageUrl + 'mini/images/me/no_login.png',
    icode: '',
    iphone: '',
    phone: '',
    isSms: false,
    timeCount: 30,
    isSmsD: false,
    timeCountD: 30,
    smsTip: '',
    isPhoneLogin: false,
    showDialogPhone: false,
    showSmsDialog: false,
    showAuthDialog: false,
    passProtocol: true,
    openLogin: false,
  },
  observers: {
    'openLogin': function(val) {
      let self = this;
      console.log("Component下的observers监听触发", val);
      if (val === true) {
        User.getUserInfo(function(userInfo) {
          /**
           * 已授权的用户自动登录成功
           * 新加弹出手机号登录
           */
          if (userInfo.phone !== '') {
            Util.cache_remove('disable_auto_login');
            self.triggerEvent('login', userInfo);
          } else {
            self.setData({
              isPhoneLogin: true
            });
          }
        }, function() {
          /**
           * 未授权的用户快捷登录失败时打开登录界面引导
           */
          self.setData({
            isPhoneLogin: false,
          });
        });
      }
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    setField: function(event) {
      let self = this;
      let _value = event.detail;
      let setData = {};
      let field = event.currentTarget.dataset.field;
      if (field && this.data.hasOwnProperty(field)) {
        if (this.data[field] !== _value) {
          setData[field] = _value;
          self.setData(setData);
        }
      }
    },
    sendSms: function(event) {
      let self = this;
      if (self.data.passProtocol !== true) {
        Util.msg('请先同意巷友用户协议');
        return false;
      }
      if (this.data.iphone === '') {
        Util.msg('请输入您的手机号码!');
        return false;
      }
      if (this.data.iphone.length !== 11) {
        Util.msg('请输入正确的手机号码!');
        return false;
      }
      Util.request({
        url: Util.api.SendSMS,
        data: {
          phone: this.data.iphone
        },
        handle: true,
        error: function(res) {
          Util.msg('服务器异常,请稍候再试');
        },
        callback: function(res) {
          let timeKey = null;
          if (res.status === 'ok') {
            self.setData({
              isSms: true,
              icode: '',
              smsTip: '30S后可重发',
              timeCount: 30,
            });
            timeKey = setInterval(function() {
              if (self.data.timeCount > 0) {
                self.setData({
                  timeCount: self.data.timeCount - 1,
                  smsTip: self.data.timeCount + 'S后可重发'
                });
              } else {
                clearInterval(timeKey);
                self.setData({
                  timeCount: 30,
                  isSms: false,
                  smsTip: ''
                });
              }
            }, 1000);
            Util.msg('验证码发送成功,请注意查收!');
          } else {
            Util.msg(res.msg);
          }
        }
      });
    },
    sendSmsD: function(event) {
      let self = this;
      if (self.data.passProtocol !== true) {
        Util.msg('请先同意巷友用户协议');
        return false;
      }
      Util.request({
        url: Util.api.SendSMS,
        data: {
          phone: this.data.phone
        },
        handle: true,
        error: function(res) {
          Util.msg('服务器异常,请稍候再试');
        },
        callback: function(res) {
          let timeKey = null;
          if (res.status === 'ok') {
            self.setData({
              isSmsD: true,
              code: '',
              smsTip: '30S后可重发',
              timeCountD: 30,
            });
            timeKey = setInterval(function() {
              if (self.data.timeCount > 0) {
                self.setData({
                  timeCountD: self.data.timeCountD - 1,
                  smsTip: self.data.timeCountD + 'S后可重发'
                });
              } else {
                clearInterval(timeKey);
                self.setData({
                  timeCountD: 30,
                  isSmsD: false,
                  smsTip: ''
                });
              }
            }, 1000);
            Util.msg('验证码发送成功,请注意查收!');
          } else {
            Util.msg(res.msg);
          }
        }
      });
    },
    smsLogin: function(event) {
      let self = this;
      if (self.data.passProtocol !== true) {
        Util.msg('请先同意巷友用户协议');
        return false;
      }
      if (this.data.iphone === '') {
        Util.msg('请输入您的手机号码!');
        return false;
      }
      if (this.data.iphone.length !== 11) {
        Util.msg('请输入正确的手机号码!');
        return false;
      }
      if (this.data.icode === '') {
        Util.msg('请输入短信验证码!');
        return false;
      }
      if (this.data.icode.length !== 6) {
        Util.msg('请输入正确的短信验证码!');
        return false;
      }
      Util.request({
        url: Util.api.MiniPhoneCodeLogin,
        data: {
          phone: this.data.iphone,
          code: this.data.icode,
          prev_uid: User.UserData.uid
        },
        handle: true,
        loading: true,
        error: function() {
          Util.msg('服务器异常,请稍候再试!');
        },
        callback: function(result) {
          let res = result.res;
          if (result.status === 'ok') {
            Util.msg('登录成功!');
            User.getUserInfoByNet(function(res) {
              Util.cache_remove('disable_auto_login');
              self.triggerEvent('login', res);
            });
          } else {
            Util.msg('验证失败:' + result.msg);
          }
        }
      })
    },
    userInfo: function(event) {
      let self = this;
      let res = event.detail;
      let app = getApp();
      console.log('按钮触发：',event);
      Util.loading('快捷登录中...');
      if (res.errMsg && res.errMsg === 'getUserInfo:fail auth deny') {
        if (self.data.cancelTotal <= 1) {
          self.setData({
            showAuthDialog: true
          });
        } else {
          Util.msg('您取消了授权,我们无法提供服务!');
        }
        self.data.cancelTotal = self.data.cancelTotal + 1;
        return false;
      }
      let autoLogin = Util.cache_get('disable_auto_login', false);
      if (autoLogin === 1) {
        res = null;
      }
      app.globalData.userInfo   = null;
      app.globalData.encryptKey = null;
      User.UserLogin(function(res) {
        Util.closeLoading();
        try {
          res.isGroup = res.grade >= 10;
        } catch (e) {
          res.isGroup = false;
        }
        console.log('UserLogin', res);
        if (!res.phone || res.phone === '') {
          Util.cache_remove('_uInfo');
          Util.cache_remove('token');
          console.log('phoneEmpty', res);
          //强行刷新jsCode
          app.globalData.userInfo   = null;
          app.globalData.encryptKey = null;
          User.getUserCode(function(result) {
            self.setData({
              showDialogPhone: true
            });
          }, function() {
            self.setData({
              showDialogPhone: true
            });
          }, 2);
        } else {
          Util.cache_remove('disable_auto_login');
          self.triggerEvent('login', res);
        }
      }, function(res) {
        Util.closeLoading();
        Util.msg('登录失败.请稍候再试-001!');
      }, res, true);
    },
    getPhoneNumber: function(event) {
      let detail = event.detail;
      let self = this;
      console.log('wx.PhoneNumber', detail);
      if (detail.errMsg && detail.errMsg !== 'getPhoneNumber:ok') {
        Util.msg('您取消了使用微信手机号码,请填写手机号码快速登录');
        return false;
      }
      /**
       * 走注册
       */
      Util.loading('正在验证手机号码...');
      User.getUserCode(function(result) {
        Util.request({
          url: Util.api.MiniPhoneLogin,
          data: {
            key: result.key,
            encryptedData: detail.encryptedData,
            iv: detail.iv
          },
          setToken: 2,
          handle: true,
          loading: true,
          error: function(res) {
            Util.msg('服务器异常,请稍候再试');
          },
          callback: function(res) {
            if (res.status === 'ok') {
              let result = res.res;
              if (result.login_success === true) {
                /**
                 * 登录成功
                 */
                Util.setToken(result.token);
                wx.setStorageSync('token', result.token);
                Util.cache_remove('disable_auto_login');
                self.triggerEvent('login', result);
              } else {
                /**
                 * 输入验证码
                 */
                self.setData({
                  showSmsDialog: true,
                  code: '',
                  phone: result.phone
                });
                Util.request({
                  url: Util.api.SendSMS,
                  data: {
                    phone: result.phone
                  },
                  handle: true,
                  error: function(res) {
                    Util.msg('服务器异常,请稍候再试');
                  },
                  callback: function(res) {
                    let timeKey;
                    if (res.status === 'ok') {
                      self.setData({
                        isSmsD: true,
                        smsTip: '30S后可重发',
                        timeCountD: 30,
                      });
                      timeKey = setInterval(function() {
                        if (self.data.timeCountD > 0) {
                          self.setData({
                            timeCountD: self.data.timeCountD - 1,
                            smsTip: self.data.timeCountD + 'S后可重发'
                          });
                        } else {
                          clearInterval(timeKey);
                          self.setData({
                            timeCountD: 30,
                            isSmsD: false,
                            smsTip: ''
                          });
                        }
                      }, 1000);
                      Util.msg('验证码发送成功,请注意查收!');
                    }
                  }
                })
              }
            } else {
              app.globalData.encryptKey = null;
              app.globalData.userInfo = null;
              Util.cache_clear();
              Util.msg(res.msg);
            }
          }
        })
      }, 2);
    },
    onConfirmSms: function(eve) {
      let data = this.data;
      let self = this;
      let app = getApp();
      let dialog = eve.detail.dialog;
      if (self.data.passProtocol !== true) {
        Util.msg('请先同意巷友用户协议');
        dialog.stopLoading();
        return false;
      }
      if (data.code.length !== 6) {
        Util.msg('请输入正确的短信验证码!');
        dialog.stopLoading();
        return false;
      }

      Util.request({
        url: Util.api.MiniPhoneCodeLogin,
        data: {
          phone: data.phone,
          code: data.code,
          prev_uid: User.UserData.uid
        },
        handle: true,
        loading: true,
        error: function() {
          dialog.stopLoading();
          Util.msg('服务器异常,请稍候再试!');
        },
        callback: function(result) {
          let res = result.res;
          if (result.status === 'ok') {
            Util.msg('登录成功!');
            User.getUserInfoByNet(function(res) {
              Util.cache_remove('disable_auto_login');
              self.triggerEvent('login', res);
            });
          } else {
            Util.msg('验证失败:' + result.msg);
            dialog.stopLoading();
          }
        }
      });
      return false;
    },
    onCloseDialogPhone: function(eve) {
      let self = this;
      User.getUserCode(function(result) {
        wx.hideTabBar();
        self.setData({
          showDialogPhone: false,
          isPhoneLogin: true
        });
      }, function() {
        wx.hideTabBar();
        self.setData({
          showDialogPhone: false,
          isPhoneLogin: true
        });
      }, 2);
    },
    onCloseAuthDialog: function(eve) {
      this.setData({
        showAuthDialog: false,
      });
    },
    cancelSmsDialog: function(eve, b) {
      console.log(eve);
      if (eve.detail !== 'cancel') {
        let dialog = eve.detail.dialog;
        this.setData({
          showSmsDialog: false,
          timeCountD: 0,
          isSmsD: false,
          code: '',
          smsTip: ''
        });
        dialog.stopLoading();
      }
    },
    onCloseSmsDialog: function(eve, b) {
      console.log(eve);
      if (eve.detail !== 'confirm') {
        this.setData({
          showSmsDialog: false,
          timeCountD: 0,
          isSmsD: false,
          code: '',
          smsTip: ''
        });
      }
    },

    switchProtocol: function(eve) {
      this.setData({
        passProtocol: !this.data.passProtocol,
      });
    },
    tipProtocol: function(eve) {
      Util.msg('请先同意巷友用户协议');
    },
    viewReadMe: function(event) {
      wx.navigateTo({
        url: '/pages/index/web/index?title=用户协议&url=' + encodeURIComponent(Util.pageUrl + 'copyright/protocol.html?v=') + Util.version,
      });
    },
  }
});
